package com.example.fortune.widget.widget;

import com.example.fortune.MainAbility;
import com.example.fortune.widget.controller.FormController;
import com.zzrv5.mylibrary.ZZRCallBack;
import com.zzrv5.mylibrary.ZZRHttp;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.FormBindingData;
import ohos.aafwk.ability.FormException;
import ohos.aafwk.ability.ProviderFormInfo;
import ohos.aafwk.content.Intent;
import ohos.app.Context;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.zson.ZSONObject;

import static com.example.fortune.widget.widget.UpdataJSData.setJson;


public class WidgetImpl extends FormController {
    private static final HiLogLabel TAG = new HiLogLabel(HiLog.DEBUG, 0x0, WidgetImpl.class.getName());
    private static final int DIMENSION_1X2 = 1;
    private static final int DIMENSION_2X4 = 3;
    private ZZRHttp zzrHttp;

    public WidgetImpl(Context context, String formName, Integer dimension) {
        super(context, formName, dimension);
    }

    @Override
    public ProviderFormInfo bindFormData() {
        HiLog.info(TAG, "bind form data");
        ZSONObject zsonObject = new ZSONObject();
        ProviderFormInfo providerFormInfo = new ProviderFormInfo();
        if (dimension == DIMENSION_1X2) {
            zsonObject.put("mini", true);
        }
        if (dimension == DIMENSION_2X4) {
            zsonObject.put("dim2X4", true);
        }
        providerFormInfo.setJsBindingData(new FormBindingData(zsonObject));

        return providerFormInfo;
    }

    @Override
    public void updateFormData(long formId, Object... vars) {
        HiLog.info(TAG, "更新数据");
        UpdataJSData.getJsonData("双鱼座", new ZZRCallBack.CallBackString() {
            public void onFailure(int code, String errorMessage) {
                //http访问出错了，此部分内容在主线程中工作;
                //可以更新UI等操作,请不要执行阻塞操作。
                HiLog.info(TAG,"数据请求失败"+code+","+errorMessage);
            }
            public void onResponse(String response) {
                //http访问成功，此部分内容在主线程中工作;
                //可以更新UI等操作，但请不要执行阻塞操作。
                HiLog.info(TAG,"数据请求成功");
                ZSONObject fortuneData = setJson(response);
                try {
                    HiLog.info(TAG,"更新数据");
                    ((MainAbility)context).updateForm(formId, new FormBindingData(fortuneData)); //4.调用MainAbility的方法updateForm()，并将formBindingData作为第二个实参
                } catch (FormException e) {
                    HiLog.info(TAG,"更新数据失败");
                }
            }
        });
    }

    @Override
    public void onTriggerFormEvent(long formId, String message) {
        HiLog.info(TAG, "handle card click event.");
    }

    @Override
    public Class<? extends AbilitySlice> getRoutePageSlice(Intent intent) {
        HiLog.info(TAG, "get the default page to route when you click card.");
        return null;
    }
}
